package m.jclecai.com.activity;

import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.ProofBean;
import m.jclecai.com.bean.UserBean;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.utils.BaseUtils;
import m.jclecai.com.utils.ChannelUtil;
import m.jclecai.com.utils.MD5;
import m.jclecai.com.utils.MyToast;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;

/**
 * 短信验证的方式登录
 */
public class ProofActivity extends BaseActivity {


    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_phone_number_code)
    EditText etPhoneNumberCode;
    @BindView(R.id.tv_send_proof)
    TextView tvSendProof;
    @BindView(R.id.text_bottom)
    TextView textBottom;

    @BindView(R.id.et_graph_code)
    EditText etGraphCode;

    @BindView(R.id.iv_gf)
    ImageView iv_gf;

    //这里我们增加图形验证码：
    @BindView(R.id.ll_showname)
    LinearLayout ll_showname;

    @BindView(R.id.et_name)
    EditText et_name;

    @Override
    public int getContentView() {
        return R.layout.activity_proof;
    }

    @Override
    public void initView() {
        setTitle("短信登录");
        leftOptionText("");
    }

    @Override
    protected void initData() {
        super.initData();
        getImgCode();
    }

    /**
     * 发送验证码
     */
    @OnClick(R.id.tv_send_proof)
    void sendProof(final View v) {
        if(TextUtils.isEmpty(etPhone.getText().toString())){
            DisPlay("请输入手机号码");
            return;
        }
        showDialog();
        BaseUtils.countDowm(this, 60, (TextView) v, "获取验证码");
        HashMap<String, String> pair = new HashMap<>();
        pair.put("phone", etPhone.getText().toString());
        pair.put("parentName", et_name.getText().toString());
        HttpManager.postAsyn(Constant_Url.NOTE_PROOF_LOGIN_URL, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                DisPlay(getString(R.string.error_network));
                dissDialog();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                ProofBean proofBean = FastOk.get(response, ProofBean.class);
                if (proofBean != null){

                    MyToast.showToast(ProofActivity.this, proofBean.getMessage());
                    if (!proofBean.getMessage().contains("验证码发送成功")){
                        if (proofBean.getMessage().contains("新用户")){
                            ll_showname.setVisibility(View.VISIBLE);
                        }
                        BaseUtils.CannelTimer((TextView) v,"获取验证码");
                    }

                }else{
                    DisPlay(getString(R.string.error_network));
                }

            }
        }, pair);
    }


    //图形验证码
    @OnClick(R.id.iv_gf)
    void getImgCode() {
        Glide.with(this).load(Constant_Url.REGISTER_RAND_URL)
                .diskCacheStrategy(DiskCacheStrategy.NONE)//禁用磁盘缓存
                .skipMemoryCache(true).into(iv_gf);//跳过内存缓存
    }

    /**
     * 登录的操作
     */
    @OnClick(R.id.text_bottom)
    void login() {
        if(TextUtils.isEmpty(etPhone.getText().toString())){
            DisPlay("请输入手机号码");
            return;
        }
        if(TextUtils.isEmpty(etPhoneNumberCode.getText().toString())){
            DisPlay("请输入验证码");
            return;
        }

        showDialog();
        //验证输入的验证码跟服务器发送过来的验证码是否一致，如果一致就登录，不一致就重新输入
        final Map<String, String> pair = new HashMap<>();
        pair.put("user", etPhone.getText().toString());
        pair.put("password", MD5.getMD5(etPhoneNumberCode.getText().toString()));
        pair.put("sessionid",etGraphCode.getText().toString());
        pair.put("channel", "android_"+ Build.VERSION.RELEASE+"_"+Build.MODEL);
        pair.put("appstore", ChannelUtil.getChannel());
        HttpManager.postAsyn(Constant_Url.CHECK_CODE_URL, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                DisPlay(getString(R.string.error_network));
                dissDialog();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                ProofBean proofBean = FastOk.get(response, ProofBean.class);
                if (proofBean != null) {
                    MyToast.showToast(ProofActivity.this, proofBean.getMessage());
                    //这里设置自动登录
                    if ("0".equals(proofBean.getStatus())){
                        HashMap<String, String> hashMap = new HashMap<>();
                        hashMap.put("user",proofBean.getUsername());
                        hashMap.put("password",proofBean.getPassword());
                        loadUserInfo(hashMap);
                    }
                }else {
                    DisPlay(getString(R.string.error_network));
                }
            }
        }, pair);
    }



    //登录后需要加载用户信息
    protected void loadUserInfo(final Map<String, String> pair) {
        showDialog();
        HttpManager.postAsyn(Constant_Url.GET_USER_INFO, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                UserBean userBean = FastOk.get(response, UserBean.class);
                if (userBean != null) {
                    if ("1011".equals(userBean.getStatus())) {
                        MyToast.showToast(ProofActivity.this, "登录失败，请尝试微信登录！");
                        PreferenceUtil.writeUser(ProofActivity.this, null);
                    } else {
                        PreferenceUtil.setAccount(ProofActivity.this, userBean.getPhone());
                        PreferenceUtil.setUserName(ProofActivity.this, TextUtils.isEmpty(userBean.getUsername())?etPhone.getText().toString():userBean.getUsername());
                        PreferenceUtil.setPassword(ProofActivity.this, pair.get("password"));
                        PreferenceUtil.setLoginStatus(ProofActivity.this, true);
                        PreferenceUtil.writeUser(ProofActivity.this, userBean);

                        //这里我们判断username是否是一个空，这里由于UserName里面做了一些处理，所这里我们要使用这个；
                        // 如果是的话，我们就认为其没有重新设置用户名和密码的；
                        JSONObject jsonObject = JSON.parseObject(response);
                        String username = jsonObject.getString("username");
                        if(TextUtils.isEmpty(username)){
                            PreferenceUtil.writeBoolean(ProofActivity.this,PreferenceUtil.IS_USER_NAME_EMPTY,true);
                        }else{
                            PreferenceUtil.writeBoolean(ProofActivity.this,PreferenceUtil.IS_USER_NAME_EMPTY,false);
                        }

                        setResult(RESULT_OK);
                        ProofActivity.this.finish();
                    }
                } else {
                    DisPlay(getString(R.string.error_network));
                }
            }
        }, pair);
    }

}
